using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TemplateWeb.Models.Repositories
{
    #region using
    using TemplateWeb.Models;
    using TemplateWeb.Helpers;
    using System.Web.Security;
    using TemplateWeb.Models.ViewModels;
    #endregion
    public class NguoiDungRepository
    {
        public int TotalItem { get; set; }
        public List<NguoiDungInfo> SelectAll(string role)
        {
            List<NguoiDungInfo> lstItem = new List<NguoiDungInfo>();
            MembershipUserCollection userCollection = Membership.GetAllUsers();
            foreach (MembershipUser user in userCollection)
            {
                var roleForUser = Roles.GetRolesForUser(user.UserName)[0];
                if (role.ToUpper() == "SUPERADMIN")
                {
                    if (roleForUser.ToUpper() != "SUPERADMIN")
                    {
                        NguoiDungInfo userInfo = new NguoiDungInfo
                        {
                            BaseInfo = new NguoiDungBaseInfo
                            {
                                ID = (Guid)user.ProviderUserKey,
                                UserName = user.UserName,
                                Email = user.Email,
                                Role = Roles.GetRolesForUser(user.UserName)[0]
                            },
                            ExtraInfo = SelectByID((Guid)user.ProviderUserKey)
                        };
                        lstItem.Add(userInfo);
                    }
                }
                else if (role.ToUpper() == "ADMIN")
                {
                    if (roleForUser.ToUpper() != "SUPERADMIN" && roleForUser.ToUpper() != "ADMIN")
                    {
                        NguoiDungInfo userInfo = new NguoiDungInfo
                        {
                            BaseInfo = new NguoiDungBaseInfo
                            {
                                ID = (Guid)user.ProviderUserKey,
                                UserName = user.UserName,
                                Email = user.Email,
                                Role = Roles.GetRolesForUser(user.UserName)[0]
                            },
                            ExtraInfo = SelectByID((Guid)user.ProviderUserKey)
                        };
                        lstItem.Add(userInfo);
                    }
                }
            }
            TotalItem = lstItem.Count;
            return lstItem;
        }

        public List<NguoiDungInfo> SelectPaging(int page, int pageSize, string role)
        {
            List<NguoiDungInfo> lstItem = new List<NguoiDungInfo>();
            MembershipUserCollection userCollection = Membership.GetAllUsers();
            foreach (MembershipUser user in userCollection)
            {
                var roleForUser = Roles.GetRolesForUser(user.UserName)[0];
                if (role.ToUpper() == "SUPERADMIN")
                {
                    if (roleForUser.ToUpper() != "SUPERADMIN")
                    {
                        NguoiDungInfo userInfo = new NguoiDungInfo
                        {
                            BaseInfo = new NguoiDungBaseInfo
                            {
                                ID = (Guid)user.ProviderUserKey,
                                UserName = user.UserName,
                                Email = user.Email,
                                Role = Roles.GetRolesForUser(user.UserName)[0]
                            },
                            ExtraInfo = SelectByID((Guid)user.ProviderUserKey)
                        };
                        lstItem.Add(userInfo);
                    }
                }
                else if (role.ToUpper() == "ADMIN")
                {
                    if (roleForUser.ToUpper() != "SUPERADMIN" && roleForUser.ToUpper() != "ADMIN")
                    {
                        NguoiDungInfo userInfo = new NguoiDungInfo
                        {
                            BaseInfo = new NguoiDungBaseInfo
                            {
                                ID = (Guid)user.ProviderUserKey,
                                UserName = user.UserName,
                                Email = user.Email,
                                Role = Roles.GetRolesForUser(user.UserName)[0]
                            },
                            ExtraInfo = SelectByID((Guid)user.ProviderUserKey)
                        };
                        lstItem.Add(userInfo);
                    }
                }
            }
            TotalItem = lstItem.Count;
            if (pageSize > 0)
            {
                int startIndex, itemCount;
                startIndex = (page - 1) * pageSize;
                itemCount = pageSize;
                if (startIndex + itemCount > lstItem.Count)
                    itemCount = lstItem.Count - startIndex;
                lstItem = lstItem.GetRange(startIndex, itemCount);
            }

            return lstItem;
        }

        public NguoiDungInfo SelectByUserName(string username)
        {
            var user = Membership.GetUser(username);
            NguoiDungInfo userInfo = new NguoiDungInfo
            {
                BaseInfo = new NguoiDungBaseInfo
                {
                    ID = (Guid)user.ProviderUserKey,
                    UserName = user.UserName,
                    Email = user.Email,
                    Role = Roles.GetRolesForUser(user.UserName)[0]
                },
                ExtraInfo = SelectByID((Guid)user.ProviderUserKey)
            };
            TotalItem = 1;
            return userInfo;
        }

        public NguoiDung SelectByID(Guid id)
        {
            var item = DataContext.Instance.NguoiDung.SingleOrDefault(dmw => dmw.ID == id);
            if (item != null)
                return item;
            return new NguoiDung();
        }

        public List<NguoiDungInfo> RetrieveByID(Guid id)
        {
            var lst = new List<NguoiDungInfo>();
            var item = DataContext.Instance.NguoiDung.SingleOrDefault(dmw => dmw.ID == id);
            var baseinfo = new NguoiDungBaseInfo
            {
                ID = item.ID,
                UserName = item.aspnet_Users.UserName,
                Email = Membership.GetUser(item.ID).Email,
                Role = Roles.GetRolesForUser(item.aspnet_Users.UserName)[0]
            };
            if (item != null)
                lst.Add(new NguoiDungInfo { BaseInfo = baseinfo, ExtraInfo = item });
            return lst;
        }

        public bool Delete(Guid id)
        {
            try
            {
                var item = DataContext.Instance.NguoiDung.FirstOrDefault(p => p.ID == id);
                DataContext.Instance.NguoiDung.DeleteObject(item);
                DataContext.Instance.SaveChanges();
                Membership.DeleteUser(Membership.GetUser(id).UserName, true);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool Save()
        {
            try
            {
                DataContext.Instance.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool Insert(AddNguoiDungViewModel obj, ref string errorText)
        {
            errorText = "";
            try
            {
                MembershipCreateStatus createStatus;
                MembershipUser newUser = Membership.CreateUser(obj.Info.BaseInfo.UserName, obj.Info.BaseInfo.Password, obj.Info.BaseInfo.Email, "What is your favouritr color?", "Black Or White", true, out createStatus);
                switch (createStatus)
                {
                    case MembershipCreateStatus.Success:
                        Roles.AddUserToRole(obj.Info.BaseInfo.UserName, obj.Info.BaseInfo.Role);
                        var extraInfo = new NguoiDung
                        {
                            ID = (Guid)newUser.ProviderUserKey
                        };
                        DataContext.Instance.NguoiDung.AddObject(extraInfo);
                        DataContext.Instance.SaveChanges();
                        break;
                    case MembershipCreateStatus.DuplicateUserName:
                        errorText = "Người dùng này đã tồn tại, vui lòng nhập vào tên người dùng khác!";
                        break;
                    case MembershipCreateStatus.DuplicateEmail:
                        errorText = "Địa chỉ Email bạn vừa nhập vào đã tồn tại, vui lòng nhập địa chỉ email khác!";
                        break;
                    case MembershipCreateStatus.InvalidEmail:
                        errorText = "Địa chỉ Email không hợp lệ, vui lòng nhập lại.";
                        break;
                    case MembershipCreateStatus.InvalidPassword:
                        errorText = "Mật khẩu phải có độ dài ít nhất 7 kí tự. Trong đó có 1 kí tự Alpha (~@#$%^&*).";
                        break;
                    default:
                        errorText = "Có 1 lỗi gì đó, tài khoản của bạn chưa được khởi tạo.";
                        break;
                }
                if (errorText != "")
                {
                    return false;
                }
                return true;
            }
            catch
            {
                errorText = "Có 1 lỗi gì đó, tài khoản của bạn chưa được khởi tạo.";
                return false;
            }
        }

        public int GetTotalItem(string role)
        {
            int count = 0;
            MembershipUserCollection userCollection = Membership.GetAllUsers();
            foreach (MembershipUser user in userCollection)
            {
                var roleForUser = Roles.GetRolesForUser(user.UserName)[0];
                if (role.ToUpper() == "SUPERADMIN")
                {
                    if (roleForUser.ToUpper() != "SUPERADMIN")
                    {
                        count++;
                    }
                }
                else if (role.ToUpper() == "ADMIN")
                {
                    if (roleForUser.ToUpper() != "SUPERADMIN" && roleForUser.ToUpper() != "ADMIN")
                    {
                        count++;
                    }
                }
            }
            return count;
        }

        public int GetTotalPage(string role)
        {
            int RecordCount = GetTotalItem(role);
            int PageSize = WebConfiguration.NumNguoiDungPerPage;
            return (RecordCount / PageSize) + ((RecordCount % PageSize == 0) ? 0 : 1);
        }

    }
}